package com.fadadianqi.mall.admin.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by aroot on 2/27/14.
 */
@Controller
public class ImageUpload {

    private static final Log log = LogFactory.getLog(ImageUpload.class);

    @RequestMapping(value = "/mall/adm/product/upload/image")
    public ResponseEntity<String> show(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {

        //获取存储目录结构
        if ( request.getParameter( "fetch" ) != null ) {
            response.setHeader( "Content-Type", "text/javascript" );
            //构造json数据
            String dirs = "[";
            dirs += "'img'";
            dirs += "]";
            String path = "updateSavePath( "+ dirs +" );";
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.add("Content-Type", "text/javascript");
            return new ResponseEntity<String>(path,
                    responseHeaders, HttpStatus.OK);
        }

        ImageUploader up = new ImageUploader(request);
        // 获取前端提交的path路径
        String dir = request.getParameter("dir");
        //普通请求中拿不到参数， 则从上传表单中拿
        if (dir == null) {
            dir = up.getParameter("dir");
        }
        up.setSavePath(dir);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(500 * 1024); //单位KB
        try {
            up.upload();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String info = "{'original':'" + up.getOriginalName() + "','url':'" + up.getUrl() + "','title':'" + up.getTitle() + "','state':'" + up.getState() + "'}";

        if(log.isDebugEnabled()) {
            log.debug("ImageUpload: " + info);
        }

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        return new ResponseEntity<String>(info,
                responseHeaders, HttpStatus.OK);
    }
}
